package com.boco.aop;

import com.boco.common.entity.HasUserEntity;
import com.boco.domain.AccountRepository;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author pandengke/pdkkpdk@163.com
 * @date 2018/11/7
 */
@Aspect
@Component
public class EntityAop {

    @Resource
    AccountRepository accountRepository;

    @Around("findAll() || query()")
    public Iterable afterFindAll(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Iterable ret = (Iterable) proceedingJoinPoint.proceed();
        if (ret == null) return null;
        for (Object o : ret) {
            assemble(o);
        }
        return ret;
    }

    @Around("findOne() || getOne()")
    public Object afterFindOne(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object ret = proceedingJoinPoint.proceed();
        if (ret == null) return null;
        assemble(ret);
        return ret;
    }

    @Pointcut("execution(* org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(..))")
    public void findAll() {
    }

    @Pointcut("execution(* org.springframework.data.jpa.repository.support.SimpleJpaRepository.findOne(..))")
    public void findOne() {
    }

    @Pointcut("execution(* org.springframework.data.jpa.repository.support.SimpleJpaRepository.getOne(..))")
    public void getOne() {
    }

    @Pointcut("execution(* com.boco.common.search.JpqlGenerator.execQuery(..))")
    protected void query() {
    }

    private void assemble(Object o) {
        if (o instanceof HasUserEntity) {
            HasUserEntity u = (HasUserEntity) o;
            u.setUser(accountRepository.findOne(u.getUserId()));
            u.setVerifyStatus(accountRepository.selectStatus(u.getUserId()));
            u.setDefaultTimes(accountRepository.selectDefaultTimes(u.getUserId()));
        }
    }

}
